package com.yksj.healthtalk.ui.dictionary;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.dictionary.DictionaryContentListFragment.DictionnaryContentListItemClickListener;

/**
 * 二级菜单(附近就医/附近药店)
 * @author zhao
 */
public class DictionarySecendActivity extends BaseFragmentActivity implements OnClickListener,DictionnaryContentListItemClickListener{
	
	RadioGroup mTabRadioGroup;
	RadioButton mTabButton1;
	RadioButton mTabButton2;
	RadioButton mTabButton3;
	RadioButton mCurrentRadioButton;//当前选择的RadioButton
	LinearLayout mTabLayout;
	DictionaryMapListFragment mapListFragment;//地图列表
	
	final List<Fragment> mCacheFragments = new ArrayList<Fragment>(4);//缓存的fragment
	List<String> mTabList;//titl集合
	String titleName;//title名字
	String mType;//类型
	String keyname;
	final MyLocationListenner locationListenner = new MyLocationListenner();
	
	
	private class HttpResponseHandler extends AsyncHttpResponseHandler{
		private final int mIndex;
		private String mTitleName;
		private String mCode;
		public HttpResponseHandler(int index,String name,String code) {
			super(DictionarySecendActivity.this);
			this.mIndex = index;
			this.mTitleName = name;
			this.mCode = code;
		}
		public void onSuccess(int statusCode, String content) {
			if(!isFinishing()){
				if(statusCode == 200 && content != null){
					onParseData(content,mIndex,mTitleName,mCode);
				}
			}
		};
	}
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.dictionary_check_content_layout);

		titleName = getIntent().getStringExtra("title");
		mType = getIntent().getStringExtra("parame");
		keyname = getIntent().getStringExtra("keyname");
		initView();
		if(getIntent().hasExtra("responseContent")){
			onParseData(getIntent().getStringExtra("responseContent"), 0, null, null);
		}else{
			initData();
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mLocationClient != null && mLocationClient.isStarted()){
			mLocationClient.stop();
		}
		mLocationClient = null;
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.title1://第一个点击
			if(mCacheFragments.size() != 0)onChangeFragment(0);
			break;
		case R.id.title2://第二个点击
			if(mCurrentRadioButton !=  mTabButton2){
				onChangeFragment(1);
			}
			break;
		case R.id.title3://第三个点击
			if(mCurrentRadioButton !=  mTabButton3){
				onChangeFragment(2);
			}
			break;
		case R.id.title_right2://地图按钮
			onChangeMapFragment();
			break;
		}
	}

	
	
	/**
	 * 内容列表点击
	 */
	@Override
	public void onContentItemClick(String name,String code,int index){
		doRequestData(code,++index,name);
	}
	
	boolean isShowingMap = false;
	/**
	 * 改变为地图显示方式
	 */
	private void onChangeMapFragment(){
		
		if(mCacheFragments.size() == 0)return;
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction  ft = fm.beginTransaction();
		Fragment fragment2 = fm.findFragmentById(R.id.fragment);
		if(fragment2 != null){//之前已经添加到界面上的进行卸载
			ft.detach(fragment2);
	  
		}
		if(!isShowingMap){
			if(mapListFragment == null){
				mapListFragment = new DictionaryMapListFragment();
				mapListFragment.setArguments(fragment2.getArguments());
				ft.add(R.id.fragment,mapListFragment);
			}else{
				ft.attach(mapListFragment);
			}
			titleRightBtn2.setBackgroundDrawable(getResources().getDrawable(R.drawable.icon_liebiao));
		}else{
			Fragment fragment = mCacheFragments.get(0);
			ft.attach(fragment);
			 titleRightBtn2.setBackgroundDrawable(getResources().getDrawable(R.drawable.icon_weizhi));
		}
		isShowingMap = !isShowingMap; 
		ft.commitAllowingStateLoss();
	}
	
	private void initView(){
		initTitle();
		
//		titleLeftBtn.setBackgroundResource(R.drawable.doctorbook_back);
		titleLeftBtn.setOnClickListener(this);
		mTabLayout = (LinearLayout)findViewById(R.id.title_indicator);
		titleTextV.setText(titleName);
		
		//显示图片按钮图标
		if("10015".equals(mType) || "10016".equals(mType)){
			titleRightBtn2.setVisibility(View.VISIBLE);
			titleRightBtn2.setBackgroundDrawable(getResources().getDrawable(R.drawable.icon_weizhi));
			titleRightBtn2.setOnClickListener(this);
		}
		
		onCreateTabLables();
	}
	
	private void initData(){
		doRequestData(null,0,null);
	}
	
	/**
	 * 解析数据
	 * @param content
	 */
	private void onParseData(String content,int index,String titleName,String mCode){
		try{
			Object object1 = new JSONTokener(content).nextValue();
			if(object1 instanceof JSONArray){//附近医院
				onUpdateListContent(content, index,titleName,mCode);
			}else if(object1 instanceof JSONObject){
				JSONObject jsonObject = (JSONObject)object1;
				Object object = jsonObject.get("data");
				if(object instanceof JSONArray){//列表显示
					onUpdateListContent(content, index,titleName,mCode);
				}else{//内容显示
					Intent intent = new Intent(this,DictionaryContentActivity.class);
					intent.putExtra("result",content);
					intent.putExtra("title",titleName);
					startActivityForResult(intent,1);	
				}
			}
		}catch(JSONException e){
			e.printStackTrace();
			return;
		}
	}
	
	/**
	 * 更新lable
	 * @param lable
	 * @param index
	 */
	private void updateTabLable(String lable,int index){
		if(mTabList.size() > 0 ){
			if(index == 0){
				if(lable != null)mTabButton1.setText(lable);
				mTabButton1.setChecked(true);
				mCurrentRadioButton = mTabButton1;
			}else if(index == 1){
				if(lable != null)mTabButton1.setText(lable);
				mTabButton2.setChecked(true);
				mTabButton2.setClickable(true);
				mTabButton2.setOnClickListener(this);
				mCurrentRadioButton = mTabButton2;
				if(lable != null)mCurrentRadioButton.setText(mTabList.get(index));
			}else if(index == 2){
				if(lable != null)mTabButton2.setText(lable);
				mTabButton3.setChecked(true);
				mTabButton3.setClickable(true);
				mTabButton3.setOnClickListener(this);
				mCurrentRadioButton = mTabButton3;
				if(lable != null)mCurrentRadioButton.setText(mTabList.get(index));
			}else if(index == 3){
				
			}
		}
	}
	
	/**
	 * 更新列表内容
	 * @param content
	 */
	private void onUpdateListContent(String content,int index,String titleName,String code){
		Bundle bundle = new Bundle();
		bundle.putString("parame",content);
		bundle.putInt("index",index);
		bundle.putString("type", mType);
		bundle.putString("code", code);
		Fragment fragment = null;
		if(("5".equals(mType) && index == 2) || "10015".equals(mType) 
				|| "10016".equals(mType) || ("10004".equals(mType) && index == 1) || ("10005".equals(mType) && index == 2) 
				|| ("10006".equals(mType) && index == 2) ){//需要筛选
			fragment = DictionaryListFragment.instantiate(this,bundle);
		}else{//不需要赛选
			fragment = DictionaryContentListFragment.instantiate(this,bundle);
		}
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction  ft = fm.beginTransaction();
		Fragment fragment2 = fm.findFragmentById(R.id.fragment);
		
		if(fragment2 != null){
			ft.detach(fragment2);
		}
		ft.add(R.id.fragment,fragment);
		ft.commitAllowingStateLoss();
		
		mCacheFragments.add(index,fragment);
		updateTabLable(titleName,index);
		
	}
	
	/**
	 * table点击切换
	 * @param index
	 */
	private void onChangeFragment(int index){
		Fragment fragment = mCacheFragments.get(index);
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction  ft = fm.beginTransaction();
		Fragment fragment2 = fm.findFragmentById(R.id.fragment);
		if(fragment2 != null){//之前已经添加到界面上的进行卸载
			ft.detach(fragment2);
		}
		ft.attach(fragment);
		ft.commitAllowingStateLoss();
		updateTabLable(null,index);
	}
	
	private void onCreateTabLables(){
		initTableArray();
		int size  = mTabList.size();
		LayoutInflater inflater = LayoutInflater.from(this);
		if(size == 2){
			mTabRadioGroup = (RadioGroup)inflater.inflate(R.layout.dictionary_two_title,null);
			LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			mTabLayout.addView(mTabRadioGroup,params);
			mTabButton1 = (RadioButton)mTabRadioGroup.findViewById(R.id.title1);
			mTabButton1.setOnClickListener(this);
			
			mTabButton2 = (RadioButton)mTabRadioGroup.findViewById(R.id.title2);
			mTabButton2 = (RadioButton)mTabRadioGroup.findViewById(R.id.title2);
		}else if(size == 3){
			mTabRadioGroup = (RadioGroup)inflater.inflate(R.layout.dictionary_three_title,null);
			LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			mTabLayout.addView(mTabRadioGroup,params);
			mTabButton1 = (RadioButton)mTabRadioGroup.findViewById(R.id.title1);
			mTabButton1.setOnClickListener(this);
			
			mTabButton2 = (RadioButton)mTabRadioGroup.findViewById(R.id.title2);
			mTabButton3 = (RadioButton)mTabRadioGroup.findViewById(R.id.title3);
		}
		//为title设置文字
		if(mTabRadioGroup != null){
			if(size == 0 )mTabRadioGroup.setVisibility(View.GONE);
			while(size > 0){
				size--;
				RadioButton radioButton = (RadioButton)mTabRadioGroup.getChildAt(size);
				radioButton.setText(mTabList.get(size));
			}
		}
	}
	
	private void initTableArray(){
		mTabList = new ArrayList<String>();
		if("1".equals(mType)){
			mTabList.add(getString(R.string.select_position));
			mTabList.add(getString(R.string.select_symptom));
		}else if("4".equals(mType)){//科室
			
		} else if("5".equals(mType)){
			mTabList.add(getString(R.string.select_area));
			mTabList.add(getString(R.string.select_type));
			mTabList.add(getString(R.string.select_hospital));
		}else if("10001".equals(mType)){//疾病查询
			mTabList.add(getString(R.string.select_position));
			mTabList.add(getString(R.string.select_disease));
		} else if("10002".equals(mType)){//按系统
			mTabList.add(getString(R.string.select_system));
			mTabList.add(getString(R.string.select_disease));
		} else if("10003".equals(mType)){//按科室
			mTabList.add(getString(R.string.select_offices));
			mTabList.add(getString(R.string.select_disease));
		} else if("10004".equals(mType)){//按名称
			mTabList.add(getString(R.string.select_usename));
			mTabList.add(getString(R.string.select_goods));
		} else if("10005".equals(mType)){//按疾病
			mTabList.add(getString(R.string.select_disease));
			mTabList.add(getString(R.string.select_usename));
			mTabList.add(getString(R.string.select_medicinal));
		} else if("10006".equals(mType)){//按用途
			mTabList.add(getString(R.string.select_use));
			mTabList.add(getString(R.string.select_usename));
			mTabList.add(getString(R.string.select_medicinal));
		}else if("10007".equals(mType) || "10008".equals(mType) || "10009".equals(mType) || //检测
				"10010".equals(mType) || "10011".equals(mType) || "10012".equals(mType)){
			mTabList.add(getString(R.string.level1));
			mTabList.add(getString(R.string.level2));
			mTabList.add(getString(R.string.level3));
		}else if("10013".equals(mType)){//按疾病
			mTabList.add(getString(R.string.select_disease));
			mTabList.add(getString(R.string.select_operation));
		}else if("10014".equals(mType)){//按部位
			mTabList.add(getString(R.string.select_position));
			mTabList.add(getString(R.string.select_operation));
		}/*else if("-100".equals(mType)){//全局查询 疾病
			
		}else if("-101".equals(mType)){//全局查询 症状
			
		}*/
	}
	
	/**
	 *请求数据
	 */
	private void doRequestData(String code,int index,String title){
		if("-100".equals(mType)){//全局查询 疾病
			if(index == 0){
				HttpRestClient.doHttpQueryDiseasesServlet("4", null, null,null,null,keyname, new HttpResponseHandler(index,title,code));
			}else{
				HttpRestClient.doHttpQueryDiseasesServlet(null, null, code,null,null,null, new HttpResponseHandler(index,title,code));
			}
			
		}else if("-101".equals(mType)){//全局查询 症状
			if(index == 0){
				HttpRestClient.doHttpQuerySituations(null, null,keyname,new HttpResponseHandler(index,title,code));
			}else{
				HttpRestClient.doHttpQuerySituations(null, code,null,new HttpResponseHandler(index,title,code));//内容
			}
		}else if("1".equals(mType)){//症状
			if(index == 0){
				HttpRestClient.doHttpQuerySituations(code, null,null,new HttpResponseHandler(index,title,code));//选择部位
			}else if(index == 1){
				HttpRestClient.doHttpQuerySituations(code, null,null,new HttpResponseHandler(index,title,code));//选择症状
			}else if(index == 2){
				HttpRestClient.doHttpQuerySituations(null, code,null,new HttpResponseHandler(index,title,code));//内容
			}
		}else if("4".equals(mType)){//科室
			if(index == 0){
				HttpRestClient.doHttpQueryOfficesServlet(null,new HttpResponseHandler(index,title,code));
			}else if(index == 1){
				HttpRestClient.doHttpQueryOfficesServlet(code, new HttpResponseHandler(index,title,code));
			}
		} else if("5".equals(mType)){//医院
			if(index == 0){
				HttpRestClient.doHttpQueryUnitsServlet("1", null, null, null, null,null,new HttpResponseHandler(index,title,code));//地区
			}else if(index == 1){
				HttpRestClient.doHttpQueryUnitsServlet("2", null, code, null, null,null, new HttpResponseHandler(index,title,code));//医院类型
			}else if(index == 2){
				//获取上一个的参数
				Fragment fragment = mCacheFragments.get((index-1));
				String parame1 = fragment.getArguments().getString("code");
				HttpRestClient.doHttpQueryUnitsServlet("2", null, parame1, code, null,null, new HttpResponseHandler(index,title,code));//等级
			}else if(index == 3){
				HttpRestClient.doHttpQueryUnitsServlet(null, null, null, null, null,code,new HttpResponseHandler(index,title,code));
			}
		}else if("10001".equals(mType) || "10002".equals(mType) || "10003".equals(mType)){//疾病查询
			if(index == 0){
				if("10001".equals(mType)){
					HttpRestClient.doHttpQueryDiseasesServlet("1", null, null,null,null,null, new HttpResponseHandler(index,title,code));
				}else if("10002".equals(mType)){
					HttpRestClient.doHttpQueryDiseasesServlet("2", null, null,null,null,null, new HttpResponseHandler(index,title,code));
				}else if("10003".equals(mType)){
					HttpRestClient.doHttpQueryDiseasesServlet("3", null, null,null,null,null, new HttpResponseHandler(index,title,code));
				}
			}else if(index == 1){
				if("10001".equals(mType)){
					HttpRestClient.doHttpQueryDiseasesServlet("1",code,null, null, null,null, new HttpResponseHandler(index,title,code));
				}else if("10002".equals(mType)){
					HttpRestClient.doHttpQueryDiseasesServlet("2",null,null, code, null,null, new HttpResponseHandler(index,title,code));
				}else if("10003".equals(mType)){
					HttpRestClient.doHttpQueryDiseasesServlet("3",null,null, null, code,null, new HttpResponseHandler(index,title,code));
				}
			}else if(index == 2){
				HttpRestClient.doHttpQueryDiseasesServlet(null, null, code,null,null,null, new HttpResponseHandler(index,title,code));
			}
		} else if("10004".equals(mType)){//按拼音
			if(index == 0){
				HttpRestClient.doHttpQueryMedicinesServlet("1",null, null,null,null,new HttpResponseHandler(index,title,code));
			}else if(index == 1){
				HttpRestClient.doHttpQueryMedicinesServlet("1",code,null,null,null,new HttpResponseHandler(index,title,code));
			}else if(index == 2){
				HttpRestClient.doHttpQueryMedicinesServlet(null, null, code, null,null,new HttpResponseHandler(index,title,code));
			}
		} else if("10005".equals(mType) || "10006".equals(mType)){//按疾病
			if(index == 0){
				if("10005".equals(mType)){
					HttpRestClient.doHttpQueryMedicinesServlet("2", null, null,null,null, new HttpResponseHandler(index,title,code));
				}else if("10006".equals(mType)){
					HttpRestClient.doHttpQueryMedicinesServlet("3", null, null,null,null, new HttpResponseHandler(index,title,code));
				}
			}else if(index == 1){
				if("10005".equals(mType)){
					HttpRestClient.doHttpQueryMedicinesServlet("2", null, null,code,null, new HttpResponseHandler(index,title,code));
				}else if("10006".equals(mType)){
					HttpRestClient.doHttpQueryMedicinesServlet("3", null, null,null,code,new HttpResponseHandler(index,title,code));
				} 
			}else if(index == 2){
				if("10005".equals(mType)){
					Fragment fragment = mCacheFragments.get((index-1));
					String parame1 = fragment.getArguments().getString("code");
					HttpRestClient.doHttpQueryMedicinesServlet("2",code, null,parame1 ,null, new HttpResponseHandler(index,title,code));
				}else if("10006".equals(mType)){
					//获取上一个的参数
					Fragment fragment = mCacheFragments.get((index-1));
					String parame1 = fragment.getArguments().getString("code");
					HttpRestClient.doHttpQueryMedicinesServlet("3", code, null,null,parame1,new HttpResponseHandler(index,title,code));
				}
			}else if(index == 3){
				if("10005".equals(mType)){
					HttpRestClient.doHttpQueryMedicinesServlet(null,null, code,null ,null,new HttpResponseHandler(index,title,code));
				}else if("10006".equals(mType)){
					HttpRestClient.doHttpQueryMedicinesServlet(null, null, code, null,null,new HttpResponseHandler(index,title,code));
				}
			}
		}else if("10007".equals(mType) || "10008".equals(mType) || "10009".equals(mType) || //检测 DictionaryCheckActivity
				"10010".equals(mType) || "10011".equals(mType) || "10012".equals(mType)){
		}else if("10013".equals(mType)){//按疾病
			if(index == 0){
				HttpRestClient.doHttpQueryTreatmentsServlet("1", null, null, null, new HttpResponseHandler(index,title,code));
			}else if(index == 1){
				HttpRestClient.doHttpQueryTreatmentsServlet("1", code, null, null, new HttpResponseHandler(index,title,code));
			}else if(index == 2){
				HttpRestClient.doHttpQueryTreatmentsServlet(null, null, code, null, new HttpResponseHandler(index,title,code));
			}
		}else if("10014".equals(mType)){//按部位
			if(index == 0){
				HttpRestClient.doHttpQueryTreatmentsServlet("2", null, null, null, new HttpResponseHandler(index,title,code));
			}else if(index == 1){
				HttpRestClient.doHttpQueryTreatmentsServlet("2", null, null, code, new HttpResponseHandler(index,title,code));
			}else if(index == 2){
				HttpRestClient.doHttpQueryTreatmentsServlet(null, null, code, null, new HttpResponseHandler(index,title,code));
			}
		}else if("10015".equals(mType)){//附近就医
			mTabLayout.setVisibility(View.GONE);
			if(index == 0){
				initLocation();
			}else if(index == 1){
				HttpRestClient.doHttpSeeDoctorServlet(null, null, null, null, null, code, null, new HttpResponseHandler(index,title,code));
			}
		}else if("10016".equals(mType)){//附近药店
			mTabLayout.setVisibility(View.GONE);
			if(index == 0){
				initLocation();
			}else if(index == 1){
				HttpRestClient.doHttpSeeDoctorServlet(null, null, null, null, null, code, null, new HttpResponseHandler(index,title,code));
			}
		}
	}
	
	LocationClient mLocationClient;
	private void initLocation(){
		if(mLocationClient == null){
			mLocationClient = new LocationClient(getApplicationContext());
			mLocationClient.registerLocationListener(locationListenner);
			LocationClientOption clientOption = new LocationClientOption();
			clientOption.setOpenGps(true);
			clientOption.setCoorType("wgs84");
			clientOption.setServiceName("com.baidu.location.service_v3.3");
			clientOption.setPoiExtraInfo(false);
			clientOption.setPriority(LocationClientOption.NetWorkFirst);
			clientOption.disableCache(false);
			clientOption.setScanSpan(5000);
			mLocationClient.setLocOption(clientOption);
		}
		mLocationClient.start();
		mLocationClient.requestLocation();
	}
	
	private class MyLocationListenner implements BDLocationListener{
		@Override
		public void onReceiveLocation(BDLocation location) {
			mLocationClient.unRegisterLocationListener(locationListenner);
			mLocationClient.stop();
			if(location != null){
				double longitude = location.getLongitude();
				double latitude = location.getLatitude();
				if("10015".equals(mType)){//附近就医
					HttpRestClient.doHttpSeeDoctorServlet("1", String.valueOf(latitude), String.valueOf(longitude), "3", null, null, null, new HttpResponseHandler(0,null,null));
				}else if("10016".equals(mType)){//附近药店
					HttpRestClient.doHttpSeeDoctorServlet("2", String.valueOf(latitude), String.valueOf(longitude), "3", null, null, null, new HttpResponseHandler(0,null,null));
				}
			}else{
				showSettingsAlert();
			}
		}
		@Override
		public void onReceivePoi(BDLocation location) {
			
		}
	}
	
	public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        // Setting Dialog Title
        alertDialog.setTitle("定位设置");
        // Setting Dialog Message
        alertDialog.setMessage("当前无法定位,\n请确定设置中的GPS和无线网络是否开启");
        // Setting Icon to Dialog
        //alertDialog.setIcon(R.drawable.delete);
 
        // On pressing Settings button
        alertDialog.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
        // on pressing cancel button
        alertDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });
        // Showing Alert Message
        alertDialog.show();
    }
}
